package moe.service;

import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import moe.config.Configuration;
import moe.dao.TagDao;
import moe.entity.Tag;
import moe.util.JSONBuilder;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.protocol.HttpContext;

public class TagHandler extends AbstractHandler {
	private static final Logger log = Logger.getLogger(PostHandler.class.getName());

	private TagDao tagDao;

	public TagHandler() {
		tagDao = new TagDao();
	}

	public void tagInfo(HttpContext context, Map<String, String[]> query) {
		HttpResponse response = getHttpResponse(context);
		if (!query.containsKey("tags")) {
			response.setStatusCode(HttpStatus.SC_BAD_REQUEST);
			return;
		}
		String[] tags = query.get("tags")[0].split(",");

		long time = System.currentTimeMillis();
		List<Tag> list = tagDao.tagInfo(tags);
		if (log.isLoggable(Level.FINE)) {
			log.fine("Query(tagInfo) time: " + (System.currentTimeMillis() - time) + "ms");
		}
		JSONBuilder builder = JSONBuilder.build().callback(getCallback(query))
				.add("tagInfo", list, false);
		String json = builder.buildString();

		sendJsonResponse(response, json);
	}

	public void tagTips(HttpContext context, Map<String, String[]> query) {
		HttpResponse response = getHttpResponse(context);
		if (!query.containsKey("tags")) {
			response.setStatusCode(HttpStatus.SC_BAD_REQUEST);
			return;
		}
		String tag = String.valueOf(query.get("tags")[0]);
		List list = tagDao.getTagTips(tag, Configuration.getTipsNumber());

		String json = JSONBuilder.build().callback(getCallback(query)).add("tagTips", list, false)
				.buildString();

		sendJsonResponse(response, json);
	}
}
